<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="pageParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="keywordChange"
        />
        <!-- 树形组件 -->
        <el-tree
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          :current-node-key="currentNodeKey"
          @node-click="nodeClick"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-permission="'import-employee'" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button v-permission="'export-employee'" size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="onRoleList(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="pageParams.page"
            :page-size="pageParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @updateEmployee="showExcelDialog=true" />
    <el-dialog
      title="分配角色"
      :visible.sync="visible"
    >
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>

      </el-checkbox-group>

      <span slot="footer" style="display: flex;justify-content: center;margin-bottom: 10px;">
        <el-button size="mini" type="primary" @click="onSubmitCheckout">确 定</el-button>
        <el-button size="mini" @click="visible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { transListToTreeData } from '@/utils'
import { getEmployeeList, exportEmployee, delEmployee, getEmployeeDetail } from '@/api/employee'
import { getDepartment } from '@/api/department'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
import { assignRolesAPI, getRoleInvokeList } from '@/api/role'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      roleList: [],
      roleIds: [],
      visible: false,
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 当前高亮的树节点 id
      currentNodeKey: 1,
      list: [],
      // 获取员工列表需要用请求参数
      pageParams: {
        page: 1,
        pagesize: 10,
        keyword: '', // 模糊查询
        departmentId: 1// 部门id 传智教育部门的id 1 , 最顶层部门,所有员工肯定属于它内部,  ==  不筛选 全部查询
      },
      total: 0, // 记录员工的总数
      showExcelDialog: false // 控制excel的弹层显示和隐藏
    }
  },
  created() {
    this.getDepartment()
    this.getEmployeeList()
  },
  methods: {
    // 树形列表
    async getDepartment() {
      // 递归方法 将列表转化成树形
      const result = await getDepartment()
      // console.log(result)
      this.depts = transListToTreeData(result.data, 0)
    },
    // 表格
    async getEmployeeList() {
      const result = await getEmployeeList(this.pageParams)
      this.list = result.data.rows
      this.total = result.data.total
    },
    // 分页
    changePage(page) {
      this.pageParams.page = page
      this.getEmployeeList()
    },
    // 搜索框
    keywordChange() {
      // 防抖
      clearTimeout(this.timeId)
      this.timeId = setTimeout(() => {
        this.getEmployeeList()
      }, 1500)
    },
    // 切换选中部门
    nodeClick(row) {
      // 点击部门节点 id
      this.pageParams.departmentId = row.id
      this.pageParams.page = 1
      // 发送请求
      this.getEmployeeList()
    },
    // 导出
    async exportEmployee() {
      const res = await exportEmployee()
      // console.log(res)
      // 使用一个npm包 直接将blob文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    // 删除员工
    async confirmDel(id) {
      await delEmployee(id)
      this.$message.success('删除员工成功')
      // 判断是否是这一页的最后一个数据，是的话删除完就跳到上一页
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getEmployeeList()
    },
    // 角色
    async onRoleList(id) {
      this.id = id
      const { data } = await getRoleInvokeList()
      this.roleList = data
      const res = await getEmployeeDetail(id)
      this.roleIds = res.data.roleIds
      console.log(res)
      this.visible = true
    },
    // 角色分配权限确定
    async onSubmitCheckout() {
      await assignRolesAPI(this.id, this.roleIds)
      this.visible = false
      this.$message.success('角色权限设置成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
